package other.edan.newpaas;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rkhd.platform.sdk.api.annotations.*;
import com.rkhd.platform.sdk.data.model.Product;
import com.rkhd.platform.sdk.exception.ApiEntityServiceException;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.model.XObject;
import com.rkhd.platform.sdk.service.XObjectService;
import com.rkhd.platform.sdk.service.XoqlService;
import org.apache.commons.lang.StringUtils;
import other.edan.newpaas.utils.*;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: pass开发以及页面需要到的自定义api
 * @Author: 黎炎松
 * @Date: 2024/8/22 10:53
 */
@RestApi(baseUrl = "/edan/custom")
public class PassCustomApi {

    private static final Logger LOGGER = LoggerFactory.getLogger();

    private static final XoqlService xoqlService = XoqlService.instance();

    public static void main(String[] args) throws ApiEntityServiceException {
        PassCustomApi passCustomApi = new PassCustomApi();

        Result result = passCustomApi.getOrderProductPrice("{\"accountId\":3677814933297768," +
                "\"productIds\":\"3380911291669155\",\"priceId\":3639987348494977,\"cooperationAgreement\":\"\",\"productOptionIds\": \"3612660783340115\"}");
        System.out.println("productPrice = " + result.getData());

        //Result minRes = passCustomApi.getMinPriceProbe("{\"priceId\":\"3519351528430148\",\"optionProduct\":\"3551789295180371\"}");
        //System.out.println("minPriceProbe = " + minRes.getData());


    }


    /**
     * 获取当前组合产品下价格最低的探头
     * @param propData
     * @return
     */
    @RestMapping(value = "/getMinPriceProbe", method = RequestMethod.POST)
    public Result getMinPriceProbe (@RestBeanParam(name = "body") String propData) {
        String MSG = "获取当前组合产品下价格最低的探头 ==> ";
        try {
            LOGGER.info(MSG + "处理开始: "+ propData);
            JSONObject productData = JSONObject.parseObject(propData);
            JSONObject minProbeObj = null;

            // 获取当前产品下的探头
            Long optionProduct = productData.getLong("optionProduct");
            String sql = "select id,optionProduct,optionProduct.isProbe__c from productOption " +
                    " where optionProduct.isProbe__c = 1 and configurableProduct = " + optionProduct;
            String optionProducts = xoqlService.query(sql).getRecords().stream().map(v -> v.getString("optionProduct")).collect(Collectors.joining(","));
            LOGGER.info(MSG + "optionProducts = "+ optionProducts);
            if (StringUtils.isBlank(optionProducts)) {
                LOGGER.info(MSG + "当前组合下没有子产品，无需处理");
                return Result.success(minProbeObj);
            }

            // 获取所有探头的价格   标准价格: productPrice  价格表价格: bookPrice
            Long priceId = productData.getLong("priceId");
            sql = String.format("select id,productId,productId.FNumber__c as FNumber,productId.productName as productName,productPrice,bookPrice,syncFlg from priceBookEntry " +
                    " where priceBookId = %s and enableFlg = 1 and productId in (%s)", priceId, optionProducts);
            List<JSONObject> priceBookList = HCXObjectService.queryAllUseXoql(sql);
            LOGGER.info(MSG + "priceBookList = "+ priceBookList.size());
            System.out.println("priceBookList = " + priceBookList);
            
            // 判断最低价格进行返回
            minProbeObj = priceBookList.stream()
                    .min(Comparator.comparingDouble(v -> {
                        Integer syncFlg = v.getInteger("syncFlg");
                        Double price = syncFlg == 1 ? v.getDouble("productPrice") : v.getDouble("bookPrice");
                        return price;
                    }))
                    .orElse(null);

            LOGGER.info(MSG + "获取成功");
            return Result.success(minProbeObj);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("获取异常:" + e.getMessage());
            return Result.error("获取异常:" + e.getMessage());
        }
    }


    /**
     * 【订单明细】计算价格：获取订单明细计算价格所需的参数
     * @param propData
     * @return
     */
    @RestMapping(value = "/getOrderProductPrice", method = RequestMethod.POST)
    public Result getOrderProductPrice(@RestBeanParam(name = "body") String propData) {
        String MSG = "获取产品价格数据 ==> ";
        try {
            // 获取传入的值
            LOGGER.info(MSG + "处理开始: "+ propData);
            if (StringUtils.isBlank(propData)) {
                return Result.error("传入参数不可为空");
            }

            // 获取产品基本信息
            JSONObject orderData = JSONObject.parseObject(propData);
            String productIds = orderData.getString("productIds"); // 产品ids
            String productOptionIds = orderData.getString("productOptionIds"); // 产品选项ids
            Long accountId = orderData.getLong("accountId"); // 客户
            Long priceId = orderData.getLong("priceId"); // 价格表
            Long cooperationAgreement = orderData.getLong("cooperationAgreement"); // 合作协议
            String sql = String.format("select id,FNumber__c,productLine__c,isProbe__c,groupSales__c,proxyProducts__c,productMarketClassification__c,devAttribute__c,areaPrice__c,reagentAttribute__c,ShifouYiqi__c " +
                    " from product where id in (%s)", productIds);
            List<JSONObject> productList = HCXObjectService.queryAllUseXoql(sql);
            LOGGER.info(MSG + "productList: "+ productList);

            // 获取客户信息
            sql = "select id,fState,authorizationLevel__c from account where id = " + accountId;
            XObject xObject = HCXObjectService.queryOne(sql);
            Integer accountState = xObject.getAttribute("fState"); // 客户省份
            Integer authorizationLevel = xObject.getAttribute("authorizationLevel__c");

            // 妇幼线
            // 查询当前客户溶液当年进货量 产品归类: productMarketClassification__c 1:共用  2: 公立型号  产品属性： devAttribute__c  2：溶液
            List<Long> yearTimeStamp = DateTools.getYearTimeStamp();
            String filterIds = productList.stream().filter(v -> Objects.equals(v.getInteger("productLine__c"), 1)).map(v -> v.getString("id")).collect(Collectors.joining(","));
            Map<Long, JSONObject> zsMap = new HashMap<>();
            if (StringUtils.isNotBlank(filterIds)) {
                sql = String.format("select porductName__c,sum(quantity__c) as jhl from salesOutReceiptDetails__c " +
                        " where porductName__c in (%s) and salesOutReceipt__c.customerName__c = %s and porductName__c.productMarketClassification__c in (1,2) and porductName__c.devAttribute__c = 2 " +
                        " and salesOutReceipt__c.dateOfPush__c between %s and %s group by porductName__c having sum(quantity__c) >= 50 ", filterIds, accountId, yearTimeStamp.get(0), yearTimeStamp.get(1));
                Map<Long, Integer> crmJhlMap = xoqlService.query(sql).getRecords().stream().collect(Collectors.toMap(e -> e.getLong("porductName__c"), e1 -> e1.getInteger("jhl")));

                // 获取已经赠送的数量
                sql = String.format("select FItemID__c,count(FItemID__c) as yzs from orderProduct where isGiveSolvent__c = 1 and orderId.accountId = %s and FItemID__c in (%s) " +
                        " and createdAt between %s and %s group by FItemID__c", accountId, filterIds, yearTimeStamp.get(0), yearTimeStamp.get(1));
                Map<Long, Integer> crmYzsMap = xoqlService.query(sql).getRecords().stream().collect(Collectors.toMap(e -> e.getLong("FItemID__c"), e1 -> e1.getInteger("yzs")));

                // 判断是否需要增送，以及赠送的数量
                for (Long id : crmJhlMap.keySet()) {
                    Integer jhl = crmJhlMap.get(id);

                    // 50送1
                    if (jhl >= 50) {
                        JSONObject zsObj = new JSONObject();
                        int giveSolventCount = jhl / 50;

                        Integer yzs = crmYzsMap.get(id);
                        if (yzs == null) yzs = 0;
                        if (yzs > 0) {
                            // 判断是否还需要赠送
                            if (giveSolventCount - yzs > 1) {
                                zsObj.put("isGiveSolvent", 1); // 赠送溶液
                                zsObj.put("giveSolventCount", giveSolventCount - yzs); // 赠送溶液数量
                            }
                        } else {
                            zsObj.put("isGiveSolvent", 1); // 赠送溶液
                            zsObj.put("giveSolventCount", giveSolventCount); // 赠送溶液数量
                        }
                        zsMap.put(id, zsObj);
                    }
                }
            }

            // 检验线 ======
            List<JSONObject> testProductList = productList.stream().filter(v -> Objects.equals(v.getInteger("productLine__c"), 5)).collect(Collectors.toList());

            // 特定蛋白 - 查询客户省份对应的价格
            int isAgent = 0; // 是否代理商
            Map<Long, Double> tddbMap = new HashMap<>();
            List<JSONObject> tddbList = testProductList.stream().filter(v -> Objects.equals(v.getInteger("proxyProducts__c"), 11)).collect(Collectors.toList());
            if (tddbList.size() > 0) {
                // 判断是否代理商
                if (authorizationLevel != null && Arrays.asList(3, 4).contains(authorizationLevel)) {
                    isAgent = 1;
                }

                if (accountState != null) {
                    String ids = tddbList.stream().map(v -> v.getString("id")).collect(Collectors.joining(","));
                    sql = String.format("select id,product__c,shengFen__c,price__c from productProvincePrice__c where shengFen__c = %s and product__c in (%s)", accountState, ids);
                    tddbMap = xoqlService.query(sql).getRecords().stream().collect(Collectors.toMap(e -> e.getLong("product__c"), e1 -> e1.getDouble("price__c"), (e, e1) -> e));
                }
                LOGGER.info(MSG + "tddbMap: "+ tddbMap);
            }

            // 获取合作协议中的价格
            Map<Long, Double> hzxxMap = new HashMap<>();
            if (cooperationAgreement != null) {
                String ids = testProductList.stream().map(v -> v.getString("id")).collect(Collectors.joining(","));
                sql = String.format("select id,deviceName__c,unitPrice__c from equipmentList__c where cooperationAgreement__c = %s and deviceName__c in (%s)", cooperationAgreement, ids);
                hzxxMap = xoqlService.query(sql).getRecords().stream().collect(Collectors.toMap(e -> e.getLong("deviceName__c"), e1 -> e1.getDouble("unitPrice__c"), (e, e1) -> e));

                sql = String.format("select id,productName__c,unitPrice__c from reagentList__c where cooperationAgreement__c = %s and productName__c in (%s)", cooperationAgreement, ids);
                Map<Long, Double> tempMap = xoqlService.query(sql).getRecords().stream().collect(Collectors.toMap(e -> e.getLong("productName__c"), e1 -> e1.getDouble("unitPrice__c"), (e, e1) -> e));
                hzxxMap.putAll(tempMap);
                LOGGER.info(MSG + "hzxxMap: "+ hzxxMap);
            }

            // 统计磁敏出库累计金额 (下单往后的一年时间)
            String cmProductIds = productList.stream().filter(v -> Objects.equals(v.getInteger("productLine__c"), 5) && Objects.equals(v.getInteger("proxyProducts__c"), 16))
                    .map(v -> v.getString("id")).collect(Collectors.joining(","));
            Map<Long, Double> cmckAmountMap = new HashMap<>();
            if (StringUtils.isNotBlank(cmProductIds)) {
                sql = String.format("select porductName__c,sum(amount__c) as amount from salesOutReceiptDetails__c " +
                        " where salesOutReceipt__c.customerName__c = %s and porductName__c in (%s) and salesOutReceipt__c.dateOfPush__c between %s and %s " +
                        " group by porductName__c having sum(amount__c) >= 500000 ", accountId, cmProductIds, HCDateUtils.getDaysBeforeLong(365), System.currentTimeMillis());
                List<JSONObject> cmProductAmountList = xoqlService.query(sql).getRecords();
                LOGGER.info(MSG + "cmProductAmountList: "+ cmProductAmountList);

                // 获取超过累计金额后的价格 Map
                if (cmProductAmountList.size() > 0) {
                    productIds = cmProductAmountList.stream().map(v -> v.getString("porductName__c")).collect(Collectors.joining(","));
                    sql = String.format("select id,productId,name,up50w__c from priceBookEntry where priceBookId = %s and enableFlg = 1 and productId in (%s)", priceId, productIds);
                    cmckAmountMap = xoqlService.query(sql).getRecords().stream().collect(Collectors.toMap(e -> e.getLong("productId"), e1 -> e1.getDouble("up50w__c")));
                }
            }


            // 区域阶梯定价 有值的情况按照客户以及产品获取到对应的价格
            // 【省份档次】: 根据客户省份获取到对应的档次
            // 【产品省份分档价格】：根据档次以及产品获取到对应的价格
            List<JSONObject> qyjtdjProductList = productList.stream().filter(v -> Objects.equals(v.getInteger("areaPrice__c"), 1)).collect(Collectors.toList());
            int isCalcQyjtdj = 0; // 是否计算阶梯区域定价
            Map<Integer, Integer> provinceLevelMap = new HashMap<>();
            List<JSONObject> produceProviceList = new ArrayList<>();
            if (qyjtdjProductList.size() > 0 && accountState != null) {
                // 判断用户取值的价格类型 默认取 市场价
                int priceType = 1;
                if (Arrays.asList(1, 2).contains(authorizationLevel)) {
                    // 经销商
                    priceType = 2;
                } else if (Arrays.asList(3, 4).contains(authorizationLevel)) {
                    // 代理
                    priceType = 3;
                }

                // 获取 【身份档次】
                sql = "select id,province__c,reagentAttribute__c,provinceL__c from provinceLevel__c where province__c = " + accountState;
                provinceLevelMap = HCXObjectService.queryAllUseXoql(sql).stream()
                        .collect(Collectors.toMap(e -> e.getIntValue("reagentAttribute__c"), e1 -> e1.getIntValue("provinceL__c"), (e, e1) -> e));

                // 获取产品的 【产品省份分档价格】 数据
                String qyjtdjProductIds = qyjtdjProductList.stream().map(v -> v.getString("id")).collect(Collectors.joining(","));
                sql = String.format("select id,priceType__c,proviceL__c,price__c,seagentAttribute__c from produceProvice__c" +
                        " where priceType__c = %s and productId__c in (%s)", priceType, qyjtdjProductIds);
                produceProviceList = HCXObjectService.queryAllUseXoql(sql);
                if (provinceLevelMap.size() > 0 && produceProviceList.size() > 0) {
                    isCalcQyjtdj = 1;
                }
            }

            // 临检试剂: 根据产品的属性获取产品选项中的价格进行判断
            List<JSONObject> ljsjProductList = productList.stream().filter(v -> Objects.equals(v.getInteger("devAttribute__c"), 4)).collect(Collectors.toList());
            Map<Long, JSONObject> ljsjProductMap = new HashMap<>();
            if (ljsjProductList.size() > 0) {
                sql = String.format("select id,name,optionProduct,amountTier__c,amountStd__c,priceStd__c,priceTier__c from productOption where amountTier__c = 1 and id in (%s)", productOptionIds);
                ljsjProductMap = HCXObjectService.queryAllUseXoql(sql).stream().collect(Collectors.toMap(e -> e.getLong("optionProduct"), e1 -> e1, (e, e1) -> e));
            }

            // 处理返回的数据
            HashMap<Long, JSONObject> productMap = new HashMap<>();
            for (JSONObject product : productList) {
                Long productId = product.getLong("id");
                Integer productLine = product.getInteger("productLine__c");

                // 赋值判断的数据
                JSONObject specialVal = new JSONObject();

                // 组合标识
                JSONArray groupSales = new JSONArray();
                if (product.containsKey("groupSales__c")) {
                    groupSales = product.getJSONArray("groupSales__c");
                }
                specialVal.put("groupSales", groupSales);

                // 是否赠送溶液
                int isGiveSolvent = 0;
                int giveSolventCount = 0;
                if (zsMap.containsKey(productId)) {
                    JSONObject obj = zsMap.get(productId);
                    isGiveSolvent = obj.getInteger("isGiveSolvent");
                    giveSolventCount = obj.getInteger("giveSolventCount");
                }
                specialVal.put("isGiveSolvent", isGiveSolvent); // 赠送溶液
                specialVal.put("giveSolventCount", giveSolventCount); // 赠送溶液数量

                // 是否探头
                Integer isProbe = product.getInteger("isProbe__c");
                specialVal.put("isProbe", isProbe != null ? isProbe : 0);

                // 省份价格
                specialVal.put("sfPrice", tddbMap.containsKey(productId) ? tddbMap.get(productId) : 0);

                // 合作协议价格
                specialVal.put("hzxxPrice", hzxxMap.containsKey(productId) ? hzxxMap.get(productId) : 0);

                // 是否代理商
                specialVal.put("isAgent", (productLine != null && productLine == 5) ? isAgent : 0);

                // 磁敏累计出库大于50W价格
                specialVal.put("isCmck", 0);
                if (cmckAmountMap.containsKey(productId)) {
                    specialVal.put("isCmck", 1);
                    specialVal.put("cmckAmount", cmckAmountMap.get(productId));
                }

                // 区域阶梯定价
                if (isCalcQyjtdj == 1 && Objects.equals(product.getInteger("areaPrice__c"), 1)) {
                    // 获取产品价格档次
                    Integer reagentAttribute = product.getInteger("reagentAttribute__c");
                    Integer provinceLevel = provinceLevelMap.get(reagentAttribute);

                    // 从集合中获取根据档次、价格类型获取价格
                    JSONObject produceProvice = produceProviceList.stream()
                            .filter(v -> Objects.equals(v.getInteger("proviceL__c"), provinceLevel) && Objects.equals(v.getInteger("seagentAttribute__c"), reagentAttribute)).findFirst().orElse(null);
                    if (produceProvice != null) {
                        specialVal.put("qyjtdyAmount", produceProvice.getDouble("price__c"));
                    }
                }

                // 临检试剂
                if (Objects.equals(product.getInteger("devAttribute__c"), 4) && ljsjProductMap.containsKey(productId)) {
                    JSONObject ljsjProduct = ljsjProductMap.get(productId);
                    specialVal.put("amountTier", ljsjProduct.getIntValue("amountTier__c")); // 是否金额阶梯定价
                    specialVal.put("amountStd", ljsjProduct.getDoubleValue("amountStd__c")); // 金额标准
                    specialVal.put("priceStd", ljsjProduct.getDoubleValue("priceStd__c")); // 定价价格
                    specialVal.put("priceTier", ljsjProduct.getDoubleValue("priceTier__c")); // 阶梯上价格
                }

                product.put("specialVal", specialVal);
                productMap.put(productId, product);
            }

            LOGGER.info("productMap:" + productMap);
            return Result.success(productMap);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("获取异常:" + e.getMessage());
            return Result.error("获取异常：" + e.getMessage());
        }
    }




}
